package com.wpre.blogsystem.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Date;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description: jwd工具类
 * User: LianBao
 * Date: 2024-12-06
 * Time: 13:16
 */
@Slf4j
public class JwtUtil {

    private static final String secret = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));//定义key
    private static final long expiration = 24 * 60 * 60 * 1000;//希望过期的时间(24小时后过期)

    //1.生成token
    public static String getToken(Map<String, Object> map) {
        return Jwts.builder()//放入载荷信息
                .setClaims(map)
                .signWith(key)//设置签名信息,需要传入一个key
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + expiration))//设置过期时间(当前时间+24小时)
                .compact();//生成token
    }

    //2.校验token
    public static Claims parseToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        //jwt解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();
            return body;
        } catch (Exception e) {
            log.error("token非法");
        }

        return null;
    }
}
